package org.lisen.scdemo.receiver.service;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AcknowledgeMode;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.ConnectException;
import java.net.SocketException;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 * @create 2020-03-0119:27
 */
//@Configuration
@Slf4j
public class MessageListenerContainer {

    @Autowired
    private ReceiverConfirmDemo receiverConfirmDemo;

    /**
     * 该bean用来使用SimpleMessageListenerContainer配置消息的监听容器。与使用application.properties配置
     * 文件起到相同的作用。可以用该类来设置：
     * 1）事务特性、事务管理器、事务属性、事务并发、是否开启事务、回滚消息
     * 2）消费者数量、最小最大数量、批量消费
     * 3）消息确认和自动确认模式、是否重回队列、异常捕获 Handler 函数
     * 4）设置消费者标签生成策略、是否独占模式、消费者属性
     * 5）具体的监听器、消息转换器
     * 比起配置文件，使用该类可以有更多的灵活性，如：在运行中通过程序方式动态的修改配置（如:消息消费者数量）
     * @param connectionFactory
     * @return
     */
    //@Bean
    public SimpleMessageListenerContainer simpleMessageListenerContainer(ConnectionFactory connectionFactory){
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        container.setConcurrentConsumers(1);
        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        container.setQueueNames("direct.queue");

        //后置处理器，接收到的消息都添加了Header请求头
        /*container.setAfterReceivePostProcessors(message -> {
            message.getMessageProperties().getHeaders().put("desc",10);
            return message;
        });*/

        container.setMessageListener(receiverConfirmDemo);

        return container;
    }

}
